package com.golddaymicromall.activity.jifen;

import android.support.annotation.NonNull;

import com.golddaymicromall.activity.panicbuying.PanicBuyingContract;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.Map;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.subscriptions.CompositeSubscription;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by lijing on 2016/10/15.
 */

public class JiFenPresenter implements JiFenContract.Presenter {
    private JiFenContract.View mView;

    @NonNull
    private CompositeSubscription mSubscriptions;

    public JiFenPresenter(JiFenContract.View view) {
        mSubscriptions = new CompositeSubscription();
        mView = checkNotNull(view, "View is not null");
        mView.setPresenter(this);
    }

    @Override
    public void getPanicBuyingInfo(String id) {
        Map<String, String> form = Maps.newHashMap();
//        Map<String, String> form = new HashMap<String, String>();
        form.put("method", "rop.product.getpoint");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("logid", id);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        Subscription subscription = OkGo.get(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> {
                    mView.showLoading();
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    mView.dismissLoading();
                    mView.showPanicBuyingInfo(s);
                }, throwable -> {
                    mView.showError();
                    throwable.printStackTrace();
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        //防止Rx内存泄漏，清空subscribe
        mSubscriptions.clear();
    }
}
